#include <assert.h>
#include <stdio.h>
#include<string.h>
#include "parse.h"

void parse_cmd(char *line, struct cmd * cmd)
{
    char *token,buf[100];
    int i=0,argc=0;
    strcpy(buf,line);
    token=strtok(buf," ");
    cmd->argv[0]=strdup(token);
    i++;
    while(token!=NULL)
    {
        token=strtok(NULL," ");
        if(token!=NULL){
            cmd->argv[i]=strdup(token);
            i++;
        }
    }
    cmd->argv[i]=NULL;
    for(i=0;cmd->argv[i]!=NULL;i++)
    {
        argc++;
    }
    cmd->argc=argc;
    cmd->input=NULL;
    cmd->output=NULL;

    for(i=0;cmd->argv[i]!=NULL;i++)
    {
       if(cmd->argv[i][0] == '<')
        {
            int j = 1;
            for (; cmd->argv[i][j-1] != '\0'; j++)
            {
                cmd->argv[i][j - 1] = cmd->argv[i][j];
            }
            cmd->input = cmd->argv[i];
            cmd->argv[i] = NULL;
        }
        else if(cmd->argv[i][0] == '>')
        {
            int j = 1;
            for (; cmd->argv[i][j-1] != '\0'; j++)
            {
                cmd->argv[i][j - 1] = cmd->argv[i][j];
            }
            cmd->output = cmd->argv[i];
            cmd->argv[i] = NULL;
        }
    }
}

void dump_cmd(struct cmd *cmd)
{
        printf("argc = %d\n", cmd->argc);
        int i;
        for (i = 0; i < cmd->argc; i++) {
             printf("argv[%d] = (%s)\n", i, cmd->argv[i]);
        }

        char *input = cmd->input ? cmd->input : "NULL";
        printf("input = (%s)\n", input);

        char *output = cmd->output ? cmd->output : "NULL";
        printf("output = (%s)\n", output);
}

int parse_pipe_cmd(char *line, struct cmd *cmdv)
{
    char *part,buf[100],*save;
    int cmdc=0;
    strcpy(buf,line);
    buf[strcspn(buf,"\n")]='\0';
    part=strtok_r(buf,"|",&save);
    struct cmd *cmd;
    while(part!=NULL)
    {
        cmd=cmdv+cmdc;
        parse_cmd(part,cmd); 
        part=strtok_r(NULL,"|",&save); 
        cmdc++;
    }
    return cmdc;
}

void dump_pipe_cmd(int cmdc, struct cmd *cmdv)
{
    int i;
    printf("pipe cmd, cmdc = %d\n", cmdc);
    for (i = 0; i < cmdc; i++) {
        struct cmd *cmd = cmdv + i;
        dump_cmd(cmd);
    }
}
